﻿#include "rfmapi.h"

#if (defined(WIN32))
#include "rfm2g_windows.h"
#endif

#include "./rfm2g_api.h"
#include "./rfmapidefine.h"

#include <QDataStream>
#include <QtEndian>


RfmApi* RfmApi::m_pInstance = nullptr;

RfmApi *RfmApi::getInstance()
{
    if(m_pInstance == nullptr)
    {
        m_pInstance = new RfmApi();
    }
    return m_pInstance;
}

int RfmApi::open()
{
    RFM2G_INT32    numDevice = 1; // 默认读取第一张卡

    QString devPath = QString::fromLocal8Bit("%1%2").arg(DEVICE_PREFIX).arg(numDevice);

    QByteArray ba = devPath.toLatin1();
    char* device = ba.data();
    RFM2G_STATUS result = RFM2gOpen( device, &m_Handle );

    if( result != RFM2G_SUCCESS )
    {
        return result;
    }

    return 0;
}

int RfmApi::read(quint32 addr, QString &value, quint32 len)
{
    char buffer[256] = {0};

//    QByteArray bufferByte = {0};
//    bufferByte.resize(len);

    RFM2G_STATUS result = RFM2gRead( m_Handle, addr, buffer, len);

    if( result != RFM2G_SUCCESS ) return result;

    QByteArray byteData;


    for(int index = len - 1; index >= 0; index--)
    {
        byteData[len - 1 - index] = buffer[index];
    }

    quint32 intValue = byteData.toHex().toUInt(nullptr, 16);
    value = QString::number(intValue);

    return 0;
}

int RfmApi::write(quint32 addr, const QString &value, int len)
{
    QByteArray byteData;
    quint32 uint8Value = value.toUInt();
    byteData.append(reinterpret_cast<const char *>(&uint8Value), sizeof(uint8Value));

    bool ok = true;

    RFM2G_STATUS result = RFM2gWrite( m_Handle, addr, (void *)byteData.data(), len );

    if( result == RFM2G_SUCCESS )
    {
        return 0;
    }

    return result;
}

void RfmApi::close()
{
    RFM2gClose(&m_Handle);

    if(m_Handle != nullptr)
    {
        delete m_Handle;
        m_Handle = nullptr;
    }
}

RfmApi::RfmApi(QObject *parent) : QObject(parent)
{
    m_Handle = nullptr;
}

RfmApi::~RfmApi()
{

}
